<?php
require_once('config/init.php');
require_once('check.php');

//接收pid
$pid = isset($_GET['pid']) ? trim($_GET['pid']) : 0;

//根据id去查询用户是否存在
$sql = "SELECT * FROM {$pre_}person WHERE id = $pid";
$person = find($sql);

//如果找不到具体的信息，就返回上一个界面
if(!$person)
{
  notice('员工不存在');
  exit;
}

//接收用来区分post请求的关键词
$action = isset($_POST['action']) ? trim($_POST['action']) : "";

//ajax post请求
if($action == "check")
{
  $success = ['result' => false, 'msg' => ''];

  //接收验证的手机号
  $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';

  //查询
  $sql = "SELECT * FROM {$pre_}person WHERE mobile LIKE '%$mobile%' AND id != $pid";
  $check = find($sql);

  if($check) //如果能找到就说明手机号已经存在了
  {
    $success['result'] = false;
    $success['msg'] = '该手机号已存在';
  }else
  {
    $success['result'] = true;
    $success['msg'] = '可以注册';
  }

  //将php的数组转换为json
  echo json_encode($success);
  exit;
}


//判断是否有提交过来数据
if($_POST)
{
  $nickname = isset($_POST['nickname']) ? trim($_POST['nickname']) : '';
  $mobile = isset($_POST['mobile']) ? trim($_POST['mobile']) : '';
  $email = isset($_POST['email']) ? trim($_POST['email']) : '';
  $address = isset($_POST['address']) ? trim($_POST['address']) : '';
  $createtime = isset($_POST['createtime']) ? trim($_POST['createtime']) : '';
  $depid = isset($_POST['depid']) ? trim($_POST['depid']) : 0;
  $jobid = isset($_POST['jobid']) ? trim($_POST['jobid']) : 0;

  //判断输入的手机号是否重复
  $sql = "SELECT * FROM {$pre_}person WHERE mobile LIKE '%$mobile%' AND id != $pid";
  $check = find($sql);

  //如果查询的结果要是不为空就说明已经添加了
  if($check)
  {
    notice("手机号已经被添加了");
    exit;
  }

  //判断入职时间
  if(empty($createtime))
  {
    $createtime = time();  //如果为空就直接给一个时间戳
  }else
  {
    $createtime = strtotime($createtime); //将标准时间转换为时间戳
  }

  //组装数据结构
  $data = [
    'nickname' => $nickname,
    'mobile' => $mobile,
    'email' => $email,
    'address' => $address,
    'createtime' => $createtime,
    'depid' => $depid,
    'jobid' => $jobid,
  ];

  //判断是否有文件上传过来
  if($_FILES['avatar']['error'] == 0 && $_FILES['avatar']['size'] > 0)
  {
    $path = "assets/uploads";  //保存文件的路径
    $upload = UploadFile("avatar", $path);
    if($upload['result'])
    {
      $data['avatar'] = $upload['data'];
    }else
    {
      //上传失败的
      notice($upload['msg']);
      exit;
    }
  }

  //调用插入数据的方法
  $affect = edit("person", $data, "id = $pid");

  if($affect)
  {
    // 有没有新图片上传
    if(isset($data['avatar']))
    {
      //先判断旧图片是否存在，如果存在 在去删除
      is_file($person['avatar']) && @unlink($person['avatar']);
    }
    
    notice("编辑员工成功", "PersonList.php");
    exit;
  }else
  {
    notice("编辑员工失败");
    exit;
  }
}


//查询部门所有数据和职位的所有数据
$sql = "SELECT * FROM {$pre_}department";
$deplist = all($sql);

$sql = "SELECT * FROM {$pre_}job";
$joblist = all($sql);

?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <?php require_once('meta.php');?>
  </head>

  <body>
    
    <?php require_once('header.php');?>

    <?php require_once('menu.php');?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">编辑员工</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="index.php">Home</a> <span class="divider">/</span></li>
            <li class="active">Index</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">
                <div class="btn-toolbar">
                    <a class="btn btn-primary" onClick="javascript:history.go(-1)"><i class="icon-list"></i> 返回列表</a>
                  <div class="btn-group">
                  </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                      <div class="tab-pane active in" id="home">
                        <form method="post" enctype="multipart/form-data">
                            <label>姓名</label>
                            <input type="text" name='nickname' value="<?php echo $person['nickname'];?>" placeholder="请输入姓名" class="input-xxlarge" required />

                            <label>手机号 - change 改变事件  添加ajax判断</label>
                            <input type="text" name='mobile' value="<?php echo $person['mobile'];?>" placeholder="请输入手机号" class="input-xxlarge" required />
                            <span id="notice" style="display: none;color:red;"></span>

                            <label>邮箱</label>
                            <input type="email" name='email' value="<?php echo $person['email'];?>" placeholder="请输入邮箱" class="input-xxlarge" required />

                            <label>地址</label>
                            <input type="text" name='address' value="<?php echo $person['address'];?>" placeholder="请输入地址" class="input-xxlarge" required />

                            <label>入职时间</label>
                            <input type="date" name='createtime' value="<?php echo date("Y-m-d", $person['createtime']);?>" placeholder="请选择入职时间" class="input-xxlarge" required />

                            <label>所在部门</label>
                            <select name="depid" class="input-xlarge" required>
                              <?php foreach($deplist as $item){?>
                                <option <?php echo $item['id']==$person['depid'] ? "selected" : "";?> value="<?php echo $item['id'];?>"><?php echo $item['name'];?></option>
                              <?php }?>
                            </select>

                            <label>所在职位</label>
                            <select name="jobid" class="input-xlarge" required>
                              <?php foreach($joblist as $item){?>
                                <option <?php echo $item['id']==$person['jobid'] ? "selected" : "";?> value="<?php echo $item['id'];?>"><?php echo $item['name'];?></option>
                              <?php }?>
                            </select>

                            <label>头像</label>
                            <a href="javascript:void(0)" style="display:inline-block;width:150px;height:150px;" onclick="avatar.click()">
                              <?php if(empty($person['avatar']) || !is_file($person['avatar'])){?>
                                <img style="width:100%;height:100%;object-fit:cover" id="preview" src="./assets/img/cover.png" />
                              <?php }else{?>
                                <img style="width:100%;height:100%;object-fit:cover" id="preview" src="<?php echo $person['avatar']?>" />
                              <?php }?>
                            </a>

                            <input type="file" id="avatar" name='avatar' class="input-xxlarge" style="display: none;" />

                            <label></label>
                            <input class="btn btn-primary" type="submit" value="提交" />
                        </form>
                      </div>
                  </div>
                </div>
                
                <footer>
                    <hr>
                    <p>&copy; 2017 <a href="#" target="_blank">copyright</a></p>
                </footer>
                    
            </div>
        </div>
    </div>
  </body>
</html>
<script>
  $("#avatar").change(function(){
    var file = this.files[0] ? this.files[0] : null

    //如果没有图片就直接 停止
    if(!file) return;

    //创建文件读取对象
    var reader = new FileReader()

    //返回base64的文件地址
    reader.readAsDataURL(file)

    //将图片对象加载成功后触发的事件
    reader.onload = function(e)
    {
      $("#preview").prop('src', e.target.result)
    }

  })

  $("input[name=mobile]").change(function(){
    var mobile = $.trim($(this).val())
    
    //正则验证

    $.ajax({
      type: 'post',
      data: {action: 'check', mobile},
      dataType: 'json',
      success: success =>
      {
        $("#notice").html(success.msg)

        if(success.result)
        {
          $("#notice").css({display: 'inline-block', color: 'green'})
        }else
        {
          $("#notice").css({display: 'inline-block', color: 'red'})
        }
      },
      error: err => 
      {
        console.log('请求错误')
        console.log(err)
      }
    })





  })
</script>